package com.swsc.xapp.utils;

public class GlobalExceptionHandler implements Thread.UncaughtExceptionHandler {
    private static Object lock = new Object();

    private GlobalExceptionHandler() {
        // Empty Constractor
    }

    private static GlobalExceptionHandler mGlobalExceptionHandler;
    private android.content.Context mContext;
    private Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler;

    public static GlobalExceptionHandler getInstance() {
        synchronized (lock) {
            if (mGlobalExceptionHandler == null) {
                synchronized (lock) {
                    if (mGlobalExceptionHandler == null) {
                        mGlobalExceptionHandler = new GlobalExceptionHandler();
                    }
                }
            }

            return mGlobalExceptionHandler;
        }
    }

    /* 初始化 */
    public void init(android.content.Context context) {
        this.mContext = context;
        Thread.setDefaultUncaughtExceptionHandler(this);
        defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
    }

    @Override
    public void uncaughtException(Thread thread, final Throwable ex) {
        if(!handleException(ex) && null != defaultUncaughtExceptionHandler){
            defaultUncaughtExceptionHandler.uncaughtException(thread, ex);
        }else {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                android.util.Log.e("全局异常", "error : ", e);
            }
            //退出程序
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
        }
    }

    private boolean handleException(Throwable ex){
        if(null == ex){
            return false;
        }
        new Thread(new Runnable() {

            @Override
            public void run() {
                android.os.Looper.prepare();

                android.widget.Toast.makeText(mContext, "很抱歉，程序出现异常，即将退出", android.widget.Toast.LENGTH_SHORT).show();

                android.os.Looper.loop();

                android.os.SystemClock.sleep(3000);

                // 将Activity的栈清空
                AppManager.removeAll(mContext);
                // 退出程序
                android.os.Process.killProcess(android.os.Process.myPid());
                // 关闭虚拟机，彻底释放内存空间
                System.exit(0);

            }
        }).start();
        return true;
    }

}
